What even is LaTeX

LaTeX is a package that can be used across systems to interact with the TeX text language. The TeX language is likely mostly used in scientific papers and math and here I use it to make mathematical formulas. But how would I use LaTeX or rather TeX in the browser? Well like for anything else there is a npm package to use it called KaTeX.

Using KaTeX

On the Node.js side of things it's as simple as installing the KaTeX package and then importing it. The only other thing you have to do is to include the stylesheet associated with KaTeX. I embedded the stylesheet directly into my html instead of downloading it and then using it. That likely would've been better as I use a css pipeline that removes unused styles but I was too lazy as of writing this.

I created something similar to the function below that takes in LaTeX input and creates html from it.

import katex from "katex";

function toHtml(latex: string) {
  return katex.renderToString(latex);
}

This function returns the raw already styled html but you can go on and style it from the outside with like color and a background. I created the following component in my repository to convert latex to html which I directly embed into my website.

import katex from "katex";

type KaTeX = { content: string | string[]; inline?: boolean };

export function KaTeX({ content, inline = false }: KaTeX) {
  if (inline) {
    const html = katex.renderToString(content as string);
    return <span>{html}</span>;
  }

  const html =
    content instanceof Array
      ? content
          .map((child) => katex.renderToString(child, { displayMode: true }))
          .join("")
      : katex.renderToString(content?.toString() || "", { displayMode: true });

  return <div>{html}</div>;
}

With this I can leverage the power of LaTeX in my website. Here are three formulas I can now make on my website without much effort.

ex2dx=π\int_{-\infty}^{\infty} e^{-x^{2}} \,dx = \sqrt{\pi}f(x)=a0+n=1(ancosnπxL+bnsinnπxL)f(x) = a_0 + \sum \limits_{n=1}^{\infty} \left(a_n \cos \frac{n \pi x}{L} + b_n \sin \frac{n \pi x}{L} \right)x=b±b24ac2ax = \frac{-b \pm \sqrt{b^{2} - 4ac}}{2a}

This is very powerful but has some drawbacks as I basically use a simple string to build my LaTeX formulas. This is fine for me tho as I won't be writing content with it 24/7 and I primarily need it in rare use cases for blog posts.

Ohh and I almost forgot I can also write LaTeX inline ex2dx=π\int_{-\infty}^{\infty} e^{-x^{2}} \,dx = \sqrt{\pi} and it's slightly different from the LaTeX block above as it's a bit squished in height.